//
// Copyright © 2021 dev. All rights reserved.
// 

import Cocoa

class ModalLoadingView: NSView {

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)

        // Drawing code here.
    }
    lazy var backgroundView: NSVisualEffectView = {
        let v = NSVisualEffectView()
        v.material = .sidebar
        v.blendingMode = .withinWindow
        v.translatesAutoresizingMaskIntoConstraints = false
        v.state = .active

        return v
    }()

    lazy var spinner: NSProgressIndicator = {
        let p = NSProgressIndicator()
        p.isIndeterminate = true
        p.style = .spinning
        p.translatesAutoresizingMaskIntoConstraints = false
        return p
    }()
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
   override  init(frame frameRect:NSRect){
        super.init(frame: frameRect)
    wantsLayer = true
    addSubview(backgroundView)
    backgroundView.addSubview(spinner)
    backgroundView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
    backgroundView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
    backgroundView.topAnchor.constraint(equalTo: topAnchor).isActive = true
    backgroundView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
    spinner.centerXAnchor.constraint(equalTo: backgroundView.centerXAnchor).isActive = true
    spinner.centerYAnchor.constraint(equalTo: backgroundView.centerYAnchor).isActive = true
   }

    func show(attachedTo view:NSView) -> ModalLoadingView {
        let v = ModalLoadingView(frame: view.bounds)
        v.show(in: view)
        return v
    }

    func show(in view:NSView)  {
        alphaValue = 0
        autoresizingMask = [.width, .height]
        spinner.startAnimation(nil)
        view.addSubview(self)
        NSAnimationContext.runAnimationGroup( {_ in
            self.alphaValue = 1
        },completionHandler: nil)
    }
    func hide()  {
        NSAnimationContext.runAnimationGroup ({ _ in
            self.spinner.stopAnimation(nil)
            self.alphaValue = 0
        }) {
            self.removeFromSuperview()
        }
    }
}
